{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "https://mp.weixin.qq.com/s?__biz=MzkxODE3NjExOQ==&mid=2247485361&idx=1&sn=e7cf25ea5b8faa9b734a1b03b6d40755&chksm=c1b42fa9f6c3a6bfe451f724e39386dfb9c5f86753fae52f148832b3d133d4b6479694cf6251&scene=178&cur_album_id=3354758663365918722#rd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入需要使用的库\n",
    "import akshare as ak\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "# 在matplotlib绘图中显示中文和负号\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib as mpl\n",
    "mpl.rcParams['font.family'] = 'STKAITI' # 中文字体'STKAITI'\n",
    "plt.rcParams['axes.unicode_minus'] = False   # 解决坐标轴负数的负号显示问题\n",
    "# 关闭警告信息\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "# 设置取数日期范围\n",
    "start_date = '20140101'\n",
    "end_date = '20231229'\n",
    "# 获取基准指数的收盘价数据\n",
    "benchmark = \"000300\"\n",
    "bars = ak.stock_zh_index_hist_csindex(symbol=benchmark, start_date=start_date, end_date=end_date)\n",
    "# 将日期设置为datetime格式\n",
    "bars['日期'] = pd.to_datetime(bars['日期'])\n",
    "prices_df = pd.DataFrame(index=bars['日期'])\n",
    "prices_df[f'{benchmark}'] = bars.set_index('日期')['收盘']\n",
    "\n",
    "# 获取股票的收盘价数据\n",
    "stock = \"600519\"\n",
    "bars = ak.stock_zh_a_hist(symbol=stock, period=\"daily\", start_date=start_date, end_date=end_date, adjust=\"qfq\")\n",
    "# 将日期设置为datetime格式\n",
    "bars['日期'] = pd.to_datetime(bars['日期'])\n",
    "prices_df[f'{stock}'] = bars.set_index('日期')['收盘']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算基准和标的股票的日收益率\n",
    "returns = prices_df.pct_change().fillna(0)\n",
    "# 计算累计超额收益率：减法版\n",
    "# 用减法计算每日的超额收益\n",
    "returns['日超额收益率_减法'] = returns[f'{stock}'] - returns[f'{benchmark}']\n",
    "# 计算减法版累计超额收益曲线\n",
    "returns['累计超额收益率_减法'] = (1 + returns['日超额收益率_减法']).cumprod() - 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算累计超额收益率：除法版\n",
    "# 用除法计算每日的超额收益\n",
    "returns['日超额收益率_除法'] = (1 + returns[f'{stock}']) / (1 + returns[f'{benchmark}']) - 1\n",
    "# 计算除法版累计超额收益曲线\n",
    "returns['累计超额收益率_除法'] = (1 + returns['日超额收益率_除法']).cumprod() - 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算基准和标的股票的累计收益率\n",
    "returns[f'{benchmark}累计收益率'] = (1 + returns[f'{benchmark}']).cumprod() - 1\n",
    "returns[f'{stock}累计收益率'] = (1 + returns[f'{stock}']).cumprod() - 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "            600519累计收益率  000300累计收益率  累计超额收益率_减法  累计超额收益率_除法\n",
      "日期                                                          \n",
      "2014-01-01     0.000000     0.000000    0.000000    0.000000\n",
      "2014-01-02     0.000000     0.000000    0.000000    0.000000\n",
      "2014-01-03     0.016876    -0.013437    0.030313    0.030726\n",
      "2014-01-06     0.044390    -0.035892    0.081641    0.083270\n",
      "2014-01-07     0.045822    -0.036167    0.083433    0.085066\n",
      "...                 ...          ...         ...         ...\n",
      "2023-12-25   -17.785517     0.441636  -66.506145  -12.643381\n",
      "2023-12-26   -17.765061     0.431877  -66.869747  -12.708450\n",
      "2023-12-27   -17.734990     0.436860  -66.522379  -12.646918\n",
      "2023-12-28   -18.327503     0.470529  -67.306873  -12.783173\n",
      "2023-12-29   -18.337834     0.477666  -67.024631  -12.733259\n",
      "\n",
      "[2436 rows x 4 columns]\n"
     ]
    }
   ],
   "source": [
    "df = returns[[f'{stock}累计收益率',f'{benchmark}累计收益率','累计超额收益率_减法','累计超额收益率_除法']]\n",
    "print(df)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "4broker",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
